package net.dfrz.oa.service.impl;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.dfrz.oa.dao.repository.UseOfficeRepository;
import net.dfrz.oa.pojo.UseOffice;
import net.dfrz.oa.pojo.User;
import net.dfrz.oa.service.UseOfficeService;
import net.dfrz.oa.utils.PageBean;

@Service
@Transactional
public class UseOfficeServiceImpl implements UseOfficeService{

	@Autowired
	private UseOfficeRepository useOfficeRepository;
	/**
	 * 无条件分页查询
	 */
	@Override
	@Transactional(readOnly=true)
	public Page<UseOffice> queryPageList(PageBean<UseOffice> pageList) {
		//排序
		Order order1 = new Order(Direction.DESC, "date");
		Sort sort = new Sort(order1);
		PageRequest pageable = new PageRequest(pageList.getPageNo()- 1, pageList.getPageSize(),sort);
		return useOfficeRepository.findAll(pageable);
	}

	@Override
	@Transactional(readOnly=true)
	public Page<UseOffice> queryPageList(PageBean<UseOffice> pageList, String query) {
		//排序
		Order order1 = new Order(Direction.DESC, "date");
		Sort sort = new Sort(order1);
		PageRequest pageable = new PageRequest(pageList.getPageNo()- 1, pageList.getPageSize(),sort);
		//将查询条件设置静态变量给匿名类传值
		final String name = query;
		//通常使用 Specification 的匿名内部类
		Specification<UseOffice> specification = new Specification<UseOffice>() {
		
			@Override
			public Predicate toPredicate(Root<UseOffice> root,
					CriteriaQuery<?> cq, CriteriaBuilder cb) {
				//联表条件查询 主表UseOffice 连接表User
				Join join = root.join(root.getModel().getSingularAttribute("user", User.class),JoinType.INNER);
				Path path = join.get("name");
				Predicate predicate = cb.like(path, "%"+name+"%");
				return predicate;
			}
		};
		return useOfficeRepository.findAll(specification, pageable);
	}

	/**
	 * 添加使用办公用品
	 */
	@Override
	public void addUseOffice(UseOffice useOffice) {
		useOfficeRepository.save(useOffice);
	}
}
